﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Runtime.Serialization;

namespace SwirlTree
{
    [Serializable()]
    public class CMYK : ISerializable
    {
        public double _c, _m, _y, _k;
        public CMYK(double c, double m, double y, double k)
        {
            _c = c;
            _m = m;
            _y = y;
            _k = k;
        }
        public static CMYK operator +(CMYK c1, CMYK c2)
        {
            return new CMYK(c1._c + c2._c, c1._m + c2._m, c1._y + c2._y, c1._k + c2._k);
        }
        public static CMYK alpha(CMYK c1, CMYK c2, double alpha)
        {
            return new CMYK(
                c2._c * alpha + c1._c * (1.0 - alpha),
                c2._m * alpha + c1._m * (1.0 - alpha),
                c2._y * alpha + c1._y * (1.0 - alpha),
                c2._k * alpha + c1._k * (1.0 - alpha));
        }
        public CMYK(SerializationInfo info, StreamingContext ctx)
        {
            this._c = (double)info.GetValue("c", typeof(double));
            this._m = (double)info.GetValue("m", typeof(double));
            this._y = (double)info.GetValue("y", typeof(double));
            this._k = (double)info.GetValue("k", typeof(double));
        }

        public void GetObjectData(SerializationInfo info, StreamingContext ctx)
        {
            info.AddValue("c", _c);
            info.AddValue("m", _m);
            info.AddValue("y", _y);
            info.AddValue("k", _k);
        }
    };

    class ColorStuff
    {
        public static CMYK RGBtoCMYK(Color col)
        {
            // normalizes red, green, blue values
            int red = col.R;
            int green = col.G;
            int blue = col.B;

            double c = (double)(255 - red) / 255;
            double m = (double)(255 - green) / 255;
            double y = (double)(255 - blue) / 255;

            double k = (double)Math.Min(c, Math.Min(m, y));

            if (k == 1.0)
            {
                return new CMYK(0, 0, 0, 1);
            }
            else
            {
                return new CMYK((c - k) / (1 - k), (m - k) / (1 - k), (y - k) / (1 - k), k);
            }
        }
        public static Color CMYKtoRGB(CMYK c)
        {
            int red = Convert.ToInt32((1 - c._c) * (1 - c._k) * 255.0);
            int green = Convert.ToInt32((1 - c._m) * (1 - c._k) * 255.0);
            int blue = Convert.ToInt32((1 - c._y) * (1 - c._k) * 255.0);

            return Color.FromArgb(red, green, blue);
        }
    }
}
